<template>
  <!-- 申请退款 -->
  <div v-if="opr == 'apply'">
    <div style="font-weight: 700;font-size: 15px;">
      <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>
      <span v-if="param.companyRole == 'zx'">申请退款</span>
      <span v-else>确认退款</span>
    </div>
    <template v-if="pageName == 'boxDeal'">
      <div style="margin-top: 20px;">
        <b>购箱信息</b>
        <el-table :data="selection" style="width: 100%">
          <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
          <el-table-column prop="carryCityName" label="购箱城市" width="180"></el-table-column>
          <el-table-column prop="createTime" label="下单日期" width="180"></el-table-column>
          <el-table-column prop="boxQuantity" label="订单箱量" width="180"></el-table-column>
          <el-table-column prop="amount" label="订单金额(￥)"></el-table-column>
        </el-table>
      </div>
      <div style="margin-top: 20px;">
        <b>退款信息</b>
        <el-table :data="selection" style="width: 100%">
          <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
          <el-table-column prop="boxQuantity" label="实购箱量" width="180"></el-table-column>
          <el-table-column prop="actualPayAmount" label="实付购箱费(￥)" width="180"></el-table-column>
          <el-table-column label="退还箱量（个）" width="180">
            <template #default="scope">
              <el-input-number v-model="scope.row.number"
                @blur="scope.row.number = scope.row.number ? scope.row.number : 1" :min="1"
                :max="scope.row.boxQuantity" />
            </template>
          </el-table-column>
          <el-table-column label="退还金额（￥）">
            <template #default="scope">
              {{ numMulti(scope.row.number, scope.row.unitPrice) || 0 }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </template>
    <template v-else>
      <div style="margin-top: 20px;">
        <b>租箱信息</b>
        <el-table :data="selection" style="width: 100%">
          <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
          <el-table-column prop="carryCityName" label="提箱城市" width="180"></el-table-column>
          <el-table-column prop="carryCityName" label="还箱城市" width="180"></el-table-column>
          <el-table-column prop="createTime" label="下单日期" width="180"></el-table-column>
          <el-table-column prop="boxQuantity" label="箱量" width="180"></el-table-column>
          <el-table-column prop="amount" label="订单金额(￥)"></el-table-column>
        </el-table>
      </div>
      <div style="margin-top: 20px;">
        <b>退款信息</b>
        <el-table :data="selection" style="width: 100%">
          {{ selection }}
          <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
          <el-table-column prop="boxQuantity" label="实租箱量" width="180"></el-table-column>
          <el-table-column prop="actualPayAmount" label="实付租箱费(￥)" width="180"></el-table-column>
          <el-table-column label="退还箱量（个）" width="180">
            <template #default="scope">
              <el-input-number v-model="scope.row.number"
                @blur="scope.row.number = scope.row.number ? scope.row.number : 1" :min="1"
                :max="scope.row.boxQuantity" />
            </template>
          </el-table-column>
          <el-table-column label="退还金额（￥）">
            <template #default="scope">
              {{ numMulti(scope.row.number, scope.row.unitPrice) || 0 }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </template>

    <el-row style="margin-top: 20px;">
      <el-col :span="6">
        应退还箱量总计：{{ totalRebackNum || 0 }}个
      </el-col>
      <el-col :span="6">
        实退还箱量总计：{{ totalRebackNum || 0 }}个
      </el-col>
      <el-col :span="6">
        应退款金额总计：￥{{ totalRebackMoney.toFixed(2) || 0 }}
      </el-col>
      <el-col v-if="param.companyRole == 'zx'" :span="6">
        优惠券：无
      </el-col>
      <el-col v-else :span="6">
        实退款金额总计：<el-input v-model="param.total" style="width: 120px;">
          <template #prepend style="border: 1px solid red;">￥</template></el-input>
      </el-col>
    </el-row>
    <el-form v-if="param.companyRole == 'sellBox'" inLine label-width="200">
      <el-form-item label="退款方式">
        <el-select v-model="param.paymentMethod" style="width:220px" placeholder="选择">
          <el-option label="对公转账" value="5" />
          <el-option label="在线支付" value="10" />
        </el-select>
      </el-form-item>
      <el-form-item label="电子回执单">
        <input type="file" />
      </el-form-item>
      <el-form-item label="退款日期">
        <el-date-picker v-model="param.paymentDate" type="date" placeholder="选择日期" />
      </el-form-item>
    </el-form>
    <div style="margin-top: 20px">
      <redStar />
      <b>退款原因</b>
      <el-input v-model="param.remark" type="textarea" show-word-limit maxlength="200"></el-input>

      <!-- <b>驳回原因</b>
      <el-input v-model="param.remark" type="textarea" show-word-limit maxlength="200"></el-input> -->
    </div>

    <div style="margin-top: 20px;width:100%;text-align: center;">
      <el-button v-if="param.companyRole == 'zx'" type="primary" @click="handleSubmit">提交</el-button>
      <div v-else>
        <el-button @click=" ">拒绝</el-button>
        <el-button type="primary" @click=" ">同意</el-button>
      </div>
    </div>
  </div>

  <!-- 确认退款 单个确认 -->
  <div v-if="opr == 'refund'">
    <div style="font-weight: 700;font-size: 15px;border-bottom: 1px solid black;padding-bottom: 20px;">
      <span style="width:3px;background-color: #2158F3;"> &nbsp</span>&nbsp;确认退款
    </div>
    <div style="margin-top: 20px;">
      <div>售箱信息</div>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-carousel trigger="click" style="margin-left: 100px;height: 200px;">
            <el-carousel-item v-for="item in rowData.mainFileList" :key="item">
              <img :src="item.url" style="height: 200px;width:100%" />
            </el-carousel-item>
          </el-carousel>
        </el-col>
        <el-col :span="12">
          <div style="font-size: 14px;text-align: left; box-sizing: border-box;padding: 0px 40px 0px 40px;">
            <el-row :gutter="10">
              <el-col :span="11">
                <span style="font-weight: bolder;font-size: 16px;">{{ rowData.carryCityName }}</span>
                <div style="margin-top: 20px;">
                  售箱城市：{{ rowData.carryCityName }}/{{ rowData.carryCountryName }}
                </div>
              </el-col>
            </el-row>
            <table style="font-size: 14px;width: 400px;margin-top: 30px; margin-bottom: 20px; text-align: left;">
              <tbody>
              <tr style="width: 100px;">
                <td>售箱单价</td>
                <td style="font-weight: 600;"> ￥&nbsp;{{ rowData.unitPrice }}</td>
              </tr>
              <tr>
                <td>箱型</td>
                <td>
                  {{ boxTypeFilter(rowData.boxType) }}
                </td>
              </tr>
              <tr>
                <td>箱况</td>
                <td>
                  {{ boxConditionFilter(rowData.boxCondition) }}
                </td>
              </tr>
              <tr>
                <td style="width:80px; ">箱量</td>
                <td>
                  <span> &nbsp;{{ rowData.boxQuantity }} &nbsp;个</span>
                </td>
              </tr>
              <tr>
                <td style="width:80px; ">实收售箱款</td>
                <td>
                  <span>￥&nbsp;{{ rowData.actualPayAmount }} </span>
                </td>
              </tr>
            </tbody>
            </table>
          </div>
        </el-col>
      </el-row>
    </div>
    <div style="margin-top: 20px">
      <div>退款信息</div>
      <el-form label-width="100" label-position="left" style="margin: 50px 0 50px 100px;">
        <el-form-item label="应退还箱量">{{ rowData.refundQuantity || 0 }} &nbsp;个</el-form-item>
        <el-form-item label="实退还箱量">{{ rowData.refundQuantity || 0 }} &nbsp;个</el-form-item>
        <el-form-item label="应退款金额">￥&nbsp;{{ rowData.refundPayAmount || 0 }}</el-form-item>
        <el-form-item label="实退款金额">￥&nbsp;
          <el-input v-model="param.refundAmount" style="width:180px"></el-input>
        </el-form-item>
        <el-form-item label="优惠券">{{ 0 }}</el-form-item>
        <el-form-item label="支付方式">
          <el-select v-model="param.paymentMethod" style="width:200px" placeholder="选择">
            <el-option label="对公转账" value="5" />
            <el-option label="在线支付" value="10" />
          </el-select>
        </el-form-item>
        <el-form-item label="电子回执单">
          <input type="file" />
        </el-form-item>
        <el-form-item label="支付日期">
          <el-date-picker v-model="param.paymentDate" style="width:200px" :editable="false" :clearable="false"
            type="date" placeholder="选择日期" />
        </el-form-item>
      </el-form>
    </div>
    <div>
      <div style="margin-top: 20px">退款原因 <b style="margin-left: 40px;">{{ rowData.remark }}</b></div>
    </div>
    <div>
      <div style="margin-top: 20px">确认信息</div>
      <el-input v-model="param.refundMark" type="textarea" rows="2" show-word-limit maxlength="200"></el-input>
    </div>
    <!-- <div style="width: 100%;text-align: center;margin-top: 20px;">
        <el-button type="primary" @click="handleRefund">提交</el-button>
      </div> -->
    <div style="margin-top: 20px;width:100%;text-align: center;">
      <el-button v-if="param.companyRole == 'zx'" type="primary" @click="handleSubmit">提交</el-button>
      <div v-else>
        <el-button @click="handleRefund(10)">拒绝</el-button>
        <el-button type="primary" @click="handleRefund(5)">同意</el-button>
      </div>
    </div>
  </div>

  <!-- 确认退款 批量确认 -->
  <div v-if="opr == 'refundPitch'">
    <div style="font-weight: 700;font-size: 15px;">
      <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>
      <span v-if="param.companyRole == 'zx'">申请退款</span>
      <span v-else>确认退款</span>
    </div>
    <div style="margin-top: 20px;">
      <b>购箱信息</b>
      <el-table :data="param.tableRefund" style="width: 100%">
        <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
        <el-table-column prop="carryCityName" label="购箱城市" width="180"></el-table-column>
        <el-table-column prop="createTime" label="下单日期" width="180"></el-table-column>
        <el-table-column prop="boxQuantity" label="订单箱量" width="180"></el-table-column>
        <el-table-column prop="amount" label="订单金额(￥)"></el-table-column>
      </el-table>
    </div>
    <div style="margin-top: 20px;">
      <b>退款信息</b>
      <el-table :data="param.tableRefund" style="width: 100%">
        <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
        <el-table-column prop="boxQuantity" label="实购箱量" width="180"></el-table-column>
        <el-table-column prop="actualPayAmount" label="实付购箱费(￥)" width="180"></el-table-column>
        <el-table-column label="退还箱量（个）" width="180">
          <template #default="scope">
            <el-input-number v-model="scope.row.number"
              @blur="scope.row.number = scope.row.number ? scope.row.number : 1" :min="1"
              :max="scope.row.boxQuantity" />
          </template>
        </el-table-column>
        <el-table-column label="退还金额（￥）">
          <template #default="scope">
            {{ numMulti(scope.row.number, scope.row.unitPrice) || 0 }}
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-row style="margin-top: 20px;">
      <el-col :span="6">
        应退还箱量总计：{{ rowData.refundQuantity || 0 }}个
      </el-col>
      <el-col :span="6">
        实退还箱量总计：{{ rowData.refundQuantity || 0 }}个
      </el-col>
      <el-col :span="6">
        应退款金额总计：￥{{ rowData.refundPayAmount || 0 }}
      </el-col>
      <el-col v-if="param.companyRole == 'zx'" :span="6">
        优惠券：无
      </el-col>
      <el-col v-else :span="6">
        实退款金额总计：<el-input v-model="param.actRefund" @blur="validateExist" style="width: 160px;">
          <template #prepend>￥</template></el-input>
      </el-col>
    </el-row>
    <el-form v-if="param.companyRole == 'sellBox'" inLine label-width="200">
      <el-form-item label="退款方式">
        <el-select v-model="param.paymentMethod" style="width:220px" placeholder="选择">
          <el-option label="对公转账" value="5" />
          <el-option label="在线支付" value="10" />
        </el-select>
      </el-form-item>
      <el-form-item label="电子回执单">
        <input type="file" />
      </el-form-item>
      <el-form-item label="退款日期">
        <el-date-picker v-model="param.paymentDate" :editable="false" :clearable="false" type="date"
          placeholder="选择日期" />
      </el-form-item>
    </el-form>
    <div style="margin-top: 20px">
      <div>
        <div style="margin-top: 20px">退款原因 <b style="margin-left: 40px;">{{ rowData.remark }}</b></div>
      </div>
      <div>
        <div style="margin-top: 20px">
          确认信息
        </div>
        <el-input v-model="param.refundMark" placeholder="拒绝退款时 必填" type="textarea" rows="2" show-word-limit
          maxlength="200"></el-input>
      </div>
    </div>
    <div style="margin-top: 20px;width:100%;text-align: center;">
      <el-button v-if="param.companyRole == 'zx'" type="primary" @click="handleSubmit">提交</el-button>
      <div v-else>
        <el-button @click="handleRefund(10)">拒绝</el-button>
        <el-button type="primary" @click="handleRefund(5)">同意</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { applyRefundRentOrderById } from '@/api/orderManage/index'
import { formatDate } from '@/utils'
import { ref, reactive, onMounted, watch, computed, onActivated } from 'vue'
import { numMulti } from '@/utils/compute'
import redStar from '@/views/components/redStar.vue';
import { getSellPurchaseBoxOrderPage, applyRefundPurchaseBoxOrderById, refundPurchaseBoxOrderById } from '@/api/boxDeal/boxBuy'
import { ElMessage } from 'element-plus';
const emit = defineEmits(['close'])

const props = defineProps({
  selection: {
    type: Array,
    default: () => []
  },
  opr: {
    type: String,
    default: ''
  },
  rowData: {
    type: Object,
    default: () => { }
  },
  pageName: {
    type: String,
    default: 'boxDeal' // boxDeal- 箱贸易 rent- 出租
  },
})

const param = reactive({
  companyRole: localStorage.getItem('companyRole') || 'zx',
  paymentMethod: '5',
  paymentDate: new Date(),
  actRefund: 0
})

onMounted(() => {
  setNumber()
  getTableData()
})
watch(() => props.selection, () => {
  setNumber()
  getTableData()
})

//申请退款 赋值
function setNumber() {
  props.selection.forEach(item => {
    item.number = 1
    item.createTime = formatDate(item.createTime, 2)
  })
}

//退款（批量） - 获取同订单号数据
function getTableData() {
  if (props.opr == 'apply') return
  let data = {
    pageNum: 1,
    pageSize: 200,
    invoiceNo: props.rowData.invoiceNo,
    invoiceStatus: 5
  }
  // 获取列表数据
  getSellPurchaseBoxOrderPage(data).then(res => {
    const statusFilter = { 5: '确认退款中', 10: '已确认退款', 15: '待退款', 20: '已退款', } //5 - 待确认 10 - 已确认 15 - 待退款 20 - 已退款
    param.tableRefund = res.data.list;
    param.tableRefund.forEach(item => {
      item.number = 1
    })
  });
}

const totalRebackNum = computed(() => {
  let total = 0
  props.selection.forEach((item: any) => {
    total += item.number
  })
  return total
})

const totalRebackMoney = computed(() => {
  let total = 0
  props.selection.forEach((item: any) => {
    total += numMulti(item.number, item.unitPrice)
  })
  return total
})

//申请退款
const handleSubmit = () => {
  if (!param.remark) {
    return ElMessage.warning('请输入退款原因')
  }
  let purchaseBoxOrder = []
  props.selection.forEach((item: any) => {
    purchaseBoxOrder.push({
      id: item.id,
      refundQuantity: item.number
    })
  })
  if (props.pageName == 'boxDeal') {
    const data = {
      "purchaseBoxOrder": JSON.stringify(purchaseBoxOrder), //"[{\"id\": 5,\"refundQuantity\": 1},{\"id\": 6,\"refundQuantity\": 1}]",
      "couponAmount": 0, //优惠
      "remark": param.remark
    }
    applyRefundPurchaseBoxOrderById(data).then(res => {
      ElMessage({ message: '退款申请已提交', type: 'success' })
      emit('close')
    })
  }
  if (props.pageName == 'rent') {
    const data = {
      "rentOrder": JSON.stringify(purchaseBoxOrder), //"[{\"id\": 5,\"refundQuantity\": 1},{\"id\": 6,\"refundQuantity\": 1}]",
      "couponAmount": 0,
      "remark": param.remark
    }
    applyRefundRentOrderById(data).then(res => {
      ElMessage({ message: '退款申请已提交', type: 'success' })
      emit('close')
    })
  }
}

//退款/驳回
const handleRefund = (flag: number) => {
  if (!param.refundMark && flag == 10) {
    return ElMessage.warning('请输入退款备注')
  }
  const data = {
    "invoiceId": props.rowData.invoiceId + '',
    "paymentMethod": param.paymentMethod - 0,
    "refundPayUrl": "[{\"name\":\"20240612/cddd81a833c64a7eab1da5c0aef8dfaf.docx\",\"returnReceiptFileName\":\"国际贸易供应链数字平台电子回执单.docx\",\"url\":\"http://47.122.3.254:9000/default/20240612/cddd81a833c64a7eab1da5c0aef8dfaf.docx\"}]",
    "refundPickupDate": "2024-09-04T18:21:19",
    "remark": param.refundMark,
    "flag": flag // 5-同意 10-驳回
  }
  refundPurchaseBoxOrderById(data).then(res => {
    // ElMessage({ message: '退款申请已提交', type: 'success' })
    emit('close')
  })
}

//过滤
const boxConditionFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{ value: 15, label: '适货' }, { value: 10, label: '次新' }, { value: 20, label: '混提' },{ value: 5, label: '全新' }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const boxTypeFilter = (val: any) => {
  let result = ''
  const boxConditionList = [{ value: 5, label: '40HQ' }, { value: 10, label: '40GP' }, { value: 15, label: '20HQ' }, { value: 20, label: '20GP' }]
  boxConditionList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const validateExist = () => {
  let val: any = param.actRefund
  if (!val) {
    param.actRefund = 0
  }
}

</script>
<style scoped></style>